package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.*;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private WeChatService weChatService;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    static List<String> DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    /**
     * 小程序登录
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        //1. 根据code调用微信api获取openid
        String openid = weChatService.getOpenid(dto.getCode());
        //2. 根据openid查询客户
        Member member = memberMapper.getByOpenId(openid);
        //3. openid为空，新增Member对象，构建数据openid
        if(null == member){
//            Member member1 = new Member();
//            member1.setOpenId(openid);
            member = Member.builder().openId(openid).build();
        }
        //4. 调用微信api获取手机号
        String phone = weChatService.getPhone(dto.getPhoneCode());
        //5. 保存或修改客户
        saveOrUpdate(member,phone);

        //6. 生成token返回
        Map<String,Object> map = new HashMap<>();
        map.put(Constants.JWT_USERID, member.getId());
        map.put(Constants.JWT_USERNAME, member.getName());

        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),jwtTokenManagerProperties.getTtl(),map);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());

        return loginVo;
    }

    /**
     * 保存或更新
     * @param member
     * @param phone
     */
    private void saveOrUpdate(Member member, String phone) {
        //判断取到的手机号与数据库中的是否一致，不一致就重新赋值
        if(ObjectUtil.notEqual(member.getPhone(),phone)){
            member.setPhone(phone);
        }

        //判断member是否存在id，存在就修改
        if(member.getId() != null){
            memberMapper.update(member);
            return;
        }

        //id为空，就是新增，词组+手机号后四位
        String nickName = DEFAULT_NICKNAME_PREFIX.get((int)(Math.random()*DEFAULT_NICKNAME_PREFIX.size())) +StringUtils.substring(phone,7);
        member.setName(nickName);
        memberMapper.save(member);
    }

    /**
     * ————————————————————————————————————————————————————————————————————————————————————————————————————————
     */

    /**
     * 根据id查询用户
     *
     * @param id 用户id
     * @return 用户信息
     */
    @Override
    public Member getById(Long id) {
        return memberMapper.selectById(id);
    }

    @Resource
    private ContractService contractService;

    @Resource
    private MemberElderService memberElderService;

    @Resource
    private OrderService orderService;

    /**
     * 分页查询用户列表
     *
     * @param page     当前页码
     * @param pageSize 每页数量
     * @param phone    手机号
     * @param nickname 昵称
     * @return 分页结果
     */
    @Override
    public PageResponse<MemberVo> page(Integer page, Integer pageSize, String phone, String nickname) {
        PageHelper.startPage(page, pageSize);
        Page<List<Member>> listPage = memberMapper.page(phone, nickname);

        PageResponse<MemberVo> pageResponse = PageResponse.of(listPage, MemberVo.class);
        List<Long> ids = pageResponse.getRecords().stream().map(MemberVo::getId).distinct().collect(Collectors.toList());

        pageResponse.getRecords().forEach(v -> {
            List<ContractVo> contractVos = contractService.listByMemberPhone(v.getPhone());
            v.setIsSign(contractVos.isEmpty() ? "否" : "是");
            List<OrderVo> orderVos = orderService.listByMemberId(v.getId());
            v.setOrderCount(orderVos.size());
            List<MemberElderVo> memberElderVos = memberElderService.listByMemberId(v.getId());
            List<String> collect = memberElderVos.stream().map(m -> m.getElderVo().getName()).collect(Collectors.toList());
            v.setElderNames(String.join(",", collect));
        });
        return pageResponse;
    }
}
